package server

import (
	"sync"
	"time"
)

type connectionHub struct {
	mu *sync.Mutex
	connmap map[string]*connection
	intervalSeconds int 

	closeCh chan struct{}
}

func NewConnHub() *connectionHub {
	return &connectionHub{
		mu: &sync.Mutex{},
		intervalSeconds: 5,
		connmap: map[string]*connection{},
		closeCh: make(chan struct{}, 1),
	}
}

func (h *connectionHub) Start() {
	go h.checkConns()
}

func (h *connectionHub) Stop() {
	h.closeCh <- struct{}{}
}

func (h *connectionHub) Add(c *connection) {
	h.mu.Lock()
	defer h.mu.Unlock()

	h.connmap[c.clientId] = c
}

func (h *connectionHub) Del(c *connection) {
	h.mu.Lock()
	defer h.mu.Unlock()

	delete(h.connmap, c.clientId)
}

func (h *connectionHub) checkConns() {
	running := true 
	for running {
		select {
		case <- h.closeCh:
			running = false
		case <- time.After(time.Duration(h.intervalSeconds) * time.Second):
			h.doCheckConns()
		}
	}
}

func (h *connectionHub) doCheckConns() {
	
}

